package cn.hftoday.core;

import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import cn.hftoday.db.*;

/**
 * Application config
 * @author lane.cn@gmail.com
 *
 */
public class ApplicationConfig {
	private static final Logger LOG = Logger.getLogger(ApplicationConfig.class);
	private static final String CONFIG_FILE = "shapeline.config.xml";
	private static ApplicationConfig _instance = null;
	private boolean inited = false;
	
	/**
	 * Constructor
	 */
	private ApplicationConfig() {
		//private constructor
	}
	
	/**
	 * get static instance
	 * @return
	 */
	public static ApplicationConfig getInstance() {
		if (_instance == null) {
			_instance = new ApplicationConfig();
		}
		return _instance;
	}

	/**
	 * load config file 
	 */
	public void load() {
		if (inited)
			return;
		
		try {
			//load config file
			/*
			 * must add env in "catalina.properties", see install document
			 */
			String file = System.getProperty("shapeline.config");
			if (file == null || file.equals("")) {
				//read app path by default
				file = CONFIG_FILE;
			}
			
			//load xml file
			Document doc = null;
			try	{
				File f = new File(file);
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				doc = builder.parse(f);
			} catch (Exception e) {
				throw new RuntimeException("error.config.not.found", e);
			}
			Element root = doc.getDocumentElement();
			
			//log config section
			try {
				NodeList list = root.getElementsByTagName("property");
				Properties properties = new Properties();
				for (int i = 0; i < list.getLength(); i ++) {
					Element item = (Element)list.item(i);
					String name = item.getAttribute("name");
					String value = item.getAttribute("value");
					properties.put(name, value);
				}
				org.apache.log4j.PropertyConfigurator.configure(properties);
			}
			catch (Exception e) {
				throw new RuntimeException("error.log.config", e);
			}
			LOG.info("-=-=-=-=-=-=-=-=-= APPLICATION START -=-=--=-=-=-=-=-=-=-=--=-");
			LOG.info("load config file: " + file);
			
			//database config section
			try {
				NodeList list = root.getElementsByTagName("connection");
				for (int i = 0; i < list.getLength(); i ++) {
					Element item = (Element)list.item(i);
					String name = item.getAttribute("name");
					String type = item.getAttribute("type");
					String connectionString = item.getAttribute("connectionstring");
					ConnectionPool.getInstance().addConnection(name, type, connectionString);
				}
			}
			catch (Exception e) {
				throw new RuntimeException("error.db.config", e);
			}
			LOG.info("load database connection pool");
			
			inited = true;
		}
		catch (Exception e) {
			throw new RuntimeException("error.app.config", e);
		}
	}
}
